package com.example.xmlparse;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private EditText edit;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button)findViewById(R.id.btnParse);
        btn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {

                // TODO Auto-generated method stub
                //Get xml parser by xml resource id
                //XmlPullParse is the base class of XmlResourceParser
                XmlResourceParser parser = getResources().getXml(R.xml.myxml);

                //StringBuilder will be used to create string which will be displayed on EditText
                StringBuilder sb = new StringBuilder();
                try{
                    //If it is not the end of the document
                    while(parser.getEventType() != XmlResourceParser.END_DOCUMENT){
                        if(parser.getEventType() == XmlResourceParser.START_TAG){
                            String name = parser.getName();
                            if(name.equals("book")){
                                String bookPrice = parser.getAttributeValue(null,"price");
                                sb.append("价格");
                                sb.append(bookPrice);

                                String bookYear = parser.getAttributeValue(null,"year");
                                sb.append("年代");
                                sb.append(bookYear);

                                String bookName = parser.nextText();
                                sb.append("书名");
                                sb.append(bookName);
                            }
                            sb.append("\n");
                        }
                        parser.next();
                    }
                    edit = (EditText) findViewById(R.id.xml);
                    edit.setText(sb.toString());
                }
                catch(XmlPullParserException e)
                {
                    e.printStackTrace();
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
        });
    }
}